package com.ruoyi.order.service.impl;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.aliyun.AlipayConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderNumberGeneratorUtil;
import com.ruoyi.common.utils.ProjectConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ios.IosVerifyUtil;
import com.ruoyi.common.wx.WxConfig;
import com.ruoyi.dynamic.domain.UserDynamicTime;
import com.ruoyi.dynamic.service.IUserDynamicTimeService;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.order.domain.OrderInfo;
import com.ruoyi.order.domain.OrderTask;
import com.ruoyi.order.mapper.OrderInfoMapper;
import com.ruoyi.order.mapper.OrderTaskMapper;
import com.ruoyi.order.service.IOrderInfoService;
import com.ruoyi.problem.domain.ProblemConsult;
import com.ruoyi.problem.mapper.ProblemConsultMapper;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.system.service.IPriceSettingService;
import com.ruoyi.thread.TaskAsync;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserCapitalFlow;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserCapitalFlowService;
import com.ruoyi.user.service.IUserTotalCapitalService;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 订单Service业务层处理
 * 
 * @author DEREK
 * @date 2023-05-22
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService 
{
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private ProblemConsultMapper problemConsultMapper;
	@Autowired
	private OrderTaskMapper orderTaskMapper;
	@Autowired
	private TaskAsync taskAsync;
	@Autowired
	private IUserDynamicTimeService userDynamicTimeService;
	@Autowired
	private IPriceSettingService priceSettingService;

	/**
	 * 查询订单
	 * 
	 * @param id 订单主键
	 * @return 订单
	 */
	@Override
	public OrderInfo selectOrderInfoById(Long id)
	{
		return orderInfoMapper.selectOrderInfoById(id);
	}

	/**
	 * 查询订单列表
	 * 
	 * @param orderInfo 订单
	 * @return 订单
	 */
	@Override
	public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
	{
		return orderInfoMapper.selectOrderInfoList(orderInfo);
	}

	/**
	 * 新增订单
	 * 
	 * @param orderInfo 订单
	 * @return 结果
	 */
	@Override
	public int insertOrderInfo(OrderInfo orderInfo)
	{
		orderInfo.setCreateTime(DateUtils.getNowDate());
		return orderInfoMapper.insertOrderInfo(orderInfo);
	}

	/**
	 * 修改订单
	 * 
	 * @param orderInfo 订单
	 * @return 结果
	 */
	@Override
	public int updateOrderInfo(OrderInfo orderInfo)
	{
		orderInfo.setUpdateTime(DateUtils.getNowDate());
		return orderInfoMapper.updateOrderInfo(orderInfo);
	}

	/**
	 * 批量删除订单
	 * 
	 * @param ids 需要删除的订单主键
	 * @return 结果
	 */
	@Override
	public int deleteOrderInfoByIds(Long[] ids)
	{
		return orderInfoMapper.deleteOrderInfoByIds(ids);
	}

	
	@Override
	public String statisticsOrderAmount(OrderInfo orderInfo) {
		return orderInfoMapper.statisticsOrderAmount(orderInfo);
	}
	
	/**
	 * 删除订单信息
	 * 
	 * @param id 订单主键
	 * @return 结果
	 */
	@Override
	public int deleteOrderInfoById(Long id)
	{
		return orderInfoMapper.deleteOrderInfoById(id);
	}

	@Autowired
	private WxConfig wxConfig;
	@Autowired
	private AlipayConfig alipayConfig;
	@Autowired
	private IUserCapitalFlowService userCapitalFlowService;
	@Autowired
	private IUserTotalCapitalService userTotalCapitalService;
	@Autowired
	private PriceSettingMapper priceSettingMapper;
	@Autowired
	private UserMapper userMapper;
	private static final String ALIPAY_NOTIFY_RESULT_FAIL = "fail";
	private static final String ALIPAY_NOTIFY_RESULT_SUCCESS = "success";

	@Override
	public String notifyFromWxpay(String notifyStr) {
		String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		try {
			// 转换成map
			Map<String, String> resultMap = WXPayUtil.xmlToMap(notifyStr);
			WXPay wxPay = new WXPay(wxConfig);
			if (wxPay.isPayResultNotifySignatureValid(resultMap)) {
				String returnCode = resultMap.get("return_code");  //状态
				String orderNo = resultMap.get("out_trade_no");//商户订单号
				String tradeNo = resultMap.get("transaction_id"); //微信订单号
				String totalfee = resultMap.get("total_fee"); //微信订单号
				if (returnCode.equals("SUCCESS")) {
					//支付成功
					String result = this.updateWhenNotify(orderNo, tradeNo,String.valueOf(Double.valueOf(totalfee) / 100));
					if (ALIPAY_NOTIFY_RESULT_SUCCESS.equals(result)) {
						xmlBack = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlBack;
	}

	@Override
	public String notifyFromAlipay(Map<String, String> params) {
		//验证签名
		try {
			boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayConfig.getAlipayCertPublicKeyRSA2(), "UTF-8", "RSA2");
			if (flag) {
				String tradeStatus = params.get("trade_status");
				//签名验证通过,验证支付结果
				if ("TRADE_FINISHED".equals(tradeStatus)
						|| "TRADE_SUCCESS".equals(tradeStatus)) {
					String orderNo = params.get("out_trade_no");
					String tradeNo = params.get("trade_no");
					String totalAmount = params.get("total_amount");

					System.out.println("支付宝回调成功============================================tradeStatus："+tradeStatus);
					//以上两个状态代表支付成功
					return this.updateWhenNotify(orderNo, tradeNo,totalAmount);
				}else{
					System.out.println("支付宝回调签名校验失败111================================================tradeStatus:"+tradeStatus);
				}
			}else {
				System.out.println("支付宝回调签名校验失败222=========flag:"+flag+"=============================params:"+params.toString());
			}
		} catch (AlipayApiException e) {
			log.error("支付宝回调签名校验失败", e);
			e.printStackTrace();
			System.out.println("支付宝回调签名校验失败=========");
		}
		return ALIPAY_NOTIFY_RESULT_FAIL;
	}

	private String updateWhenNotify(String orderNo, String tradeNo,String total){
		//根据商家订单号查询订单信息

		OrderInfo orderInfo = this.getOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
		if (Objects.isNull(orderInfo)) {
			log.error("订单号不存在,支付失败 :" + orderNo);
			return ALIPAY_NOTIFY_RESULT_FAIL;
		}
		//查看订单状态是否已经是已支付
		if (ProjectConstant.COMMON_STATUS_AVAILABLE == Integer.parseInt(orderInfo.getOrderStatus())) {
			log.error("订单已支付,忽略重复调用 :" + orderNo);
			return ALIPAY_NOTIFY_RESULT_SUCCESS;
		}
		//以上校验通过,更新相关信息
		orderInfo.setOrderStatus("1");//已支付
		orderInfo.setTradeNo(tradeNo);//商户交易号
		orderInfo.setOrderUpdateTime(new Date());
		orderInfo.setActualAmount(new BigDecimal(total));
		//更新订单信息
		this.updateById(orderInfo);
		// 更新相关业务操作
		this.updateBusiness(orderInfo);
		return ALIPAY_NOTIFY_RESULT_SUCCESS;
	}

	/**
	 * 根据订单支付状态更新相关业务
	 * @param orderInfo
	 * @throws Exception
	 */
	private void updateBusiness(OrderInfo orderInfo) {
		try {
			if(Objects.nonNull(orderInfo)){
				// 删除订单的定时任务
				List<OrderTask> idList = orderTaskMapper.selectList(new LambdaQueryWrapper<OrderTask>().eq(OrderTask::getOrderNo, orderInfo.getOrderNo()).eq(OrderTask::getStatus, 0));
				if(CollectionUtil.isNotEmpty(idList)) {
					orderTaskMapper.deleteBatchIds(idList.stream().map(OrderTask::getId).collect(Collectors.toList()));
				}
				// 获取订单对应业务类型
				String orderType = orderInfo.getOrderType();
				PriceSetting one = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getId, orderInfo.getRelatedId()));
				switch (orderType){
				case "1"://充值VIP
					rechargeUserVip(orderInfo.getPayUserId(),one,orderInfo.getToUserId(),orderInfo.getOrderNo(),orderInfo.getPayType());
					//添加账单流水信息
					//addCapotalFlow(orderInfo.getOrderNo(), 2, 1, orderInfo.getOrderAmount(), orderInfo.getPayUserId(), 1L, "VIP充值", Integer.valueOf(orderInfo.getPayType()), 1, orderInfo.getRelatedId(),one.getPriceName());
					//taskAsync.sendSystemMsg(orderInfo.getPayUserId(), 0l, 14, "","");
					taskAsync.addUserCapitalFlow(orderInfo.getPayUserId(), orderInfo.getToUserId(), 1, orderInfo.getOrderAmount(), Integer.valueOf(orderInfo.getPayType()), 0);
					break;
					// 余额充值
				case "6":
					BigDecimal amount = BigDecimal.ZERO;
					if(null != one) {
						amount = one.getOriginalPrice();
						if (one.getCurrentPrice().compareTo(orderInfo.getActualAmount()) == 1){
							amount = orderInfo.getActualAmount();
						}
					}else {
						amount = orderInfo.getActualAmount();
					}
					String remark = "花粉充值";
					BigDecimal coupAmount = amount;
					// 是否使用了优惠券
					if(null != orderInfo.getCouponId()) {
						PriceSetting couponSet = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getId, orderInfo.getCouponId()).eq(PriceSetting::getPriceType, "优惠券")
								.eq(PriceSetting::getEnabled, 1).last("limit 1"));
						if(null != couponSet && null != couponSet.getCurrentPrice() && null != couponSet.getOriginalPrice()) {
							if(amount.compareTo(couponSet.getCurrentPrice()) >= 0) {
								remark = remark+"-使用优惠券,"+couponSet.getPriceName();
								coupAmount =  amount.add(couponSet.getOriginalPrice());
							}
						}
					}
					//增加钻石
					userTotalCapitalService.initUserTotalCapital("3", orderInfo.getPayUserId(), coupAmount, 1);
					//添加账单流水信息
					//					addCapotalFlow(orderInfo.getOrderNo(), 1, 4, amount, orderInfo.getPayUserId(), 1L, remark, Integer.valueOf(orderInfo.getPayType()), 1, orderInfo.getRelatedId(),one.getPriceName());
					// 推送消息
					//taskAsync.sendSystemMsg(orderInfo.getPayUserId(), 0l, 17, "用户充值","您已成功充值"+amount+"元！");
					taskAsync.addUserCapitalFlow(orderInfo.getPayUserId(), orderInfo.getToUserId(), 3, orderInfo.getOrderAmount(), Integer.valueOf(orderInfo.getPayType()), 0);
					break;
					// 打赏咨询
				case "3":
					if(StringUtils.isNotEmpty(orderInfo.getExtend())) {
						ProblemConsult consult = JSONObject.parseObject(orderInfo.getExtend(), ProblemConsult.class);
						problemConsultMapper.insert(consult);
						orderInfo.setRelatedId(consult.getId());
						orderInfoMapper.updateById(orderInfo);
						taskAsync.sendSystemMsg(orderInfo.getPayUserId(), 0l, 4, "", "");
					}
					break;
				case "2": // 活动支付 
					BigDecimal toAmount = priceSettingService.qryScale("activityProportion", orderInfo.getOrderAmount());
					List<UserDynamicTime> timeList = userDynamicTimeService.list(new LambdaQueryWrapper<UserDynamicTime>().in(UserDynamicTime::getId, orderInfo.getExtend())
							.eq(UserDynamicTime::getIsReservation, 0));
					if(CollectionUtil.isNotEmpty(timeList)) {
						String userContent = ""; // 报名活动推送消息内容 - 用户
						String consultantCount = ""; // 报名活动推送消息内容 - 咨询师
						String times = "";
						for (UserDynamicTime time : timeList) {
							time.setReservationTime(new Date());
							time.setReservationUserId(orderInfo.getPayUserId());
							time.setIsReservation(1);
							times += time.getVeryDate()+" "+time.getBegTime()+"、";
						}
						// 增加余额
						userTotalCapitalService.initUserTotalCapital("1", orderInfo.getToUserId(), toAmount, 1);
						times = times.substring(0,times.length()-1);
						userContent = "您已成功报名"+times+"的活动，点击查看详情！";
						consultantCount = "您的活动"+times+"已被预约！";
						taskAsync.sendSystemMsg(orderInfo.getPayUserId(), 0l, 9, String.valueOf(orderInfo.getRelatedId()), userContent);
						taskAsync.sendSystemMsg(orderInfo.getToUserId(), 0l, 10, String.valueOf(orderInfo.getRelatedId()), consultantCount);
					}
					userDynamicTimeService.updateBatchById(timeList);
					taskAsync.addOrderMsg(orderInfo.getPayUserId(),orderInfo.getToUserId(), 2, orderInfo.getRemark(),orderInfo.getOrderAmount(),toAmount,Integer.valueOf(orderInfo.getPayType()));

					break;
				case "4": // 单次咨询支付
					//					toAmount = priceSettingService.qryScale("consultProportion", orderInfo.getOrderAmount());
					taskAsync.addOrderMsg(orderInfo.getPayUserId(),orderInfo.getToUserId(), 4, orderInfo.getRemark(),orderInfo.getOrderAmount(),orderInfo.getOrderAmount(),Integer.valueOf(orderInfo.getPayType()));
					//					// 增加余额
					//					userTotalCapitalService.initUserTotalCapital("1", orderInfo.getToUserId(), toAmount, 1);
					taskAsync.sendSystemMsg(orderInfo.getToUserId(), orderInfo.getPayUserId(), 3, orderInfo.getOrderNo(), orderInfo.getRemark());
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String orderType = orderInfo.getOrderType();
			Integer businessType = 0;
			Integer type = 0;
			Long toUserId = -1L;
			String remark = "";
			if("6".equals(orderType)) {
				businessType = 4;
				type = 1;
				toUserId = 1L;
				remark = "钻石充值异常："+e.getMessage();
			}else if("8".equals(orderType)) {
				businessType = 13;
				type = 6;
				toUserId = 7L;
				remark = "7天体验卡，跳过真人认证 直接进入平台异常："+e.getMessage();
			}
			// 异常
			addCapotalFlow(orderInfo.getOrderNo(), type, businessType, orderInfo.getOrderAmount(), orderInfo.getPayUserId(), toUserId, remark, Integer.valueOf(orderInfo.getPayType()), 0, orderInfo.getRelatedId(),"异常");
		}
	}

	// 充值VIP逻辑
	private void rechargeUserVip(Long userId,PriceSetting one,Long toUserId,String orderNo,String payType) {
		User user = userMapper.selectById(userId);
		if(null == user) {
			return;
		}
		if(null == user.getVipExpireTime() || !com.ruoyi.common.utils.date.DateUtils.isOverdue(new Date(), user.getVipExpireTime())) {
			Calendar curr = Calendar.getInstance();
			curr.setTime(new Date());
			//			if("1".equals(one.getExtend2())) { // 月
			//				curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+Integer.valueOf(one.getPayCode()));
			//			}else { // 天
			//				curr.set(Calendar.DATE,curr.get(Calendar.DATE)+Integer.valueOf(one.getPayCode()));
			//			}
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+Integer.valueOf(one.getPayCode()));
			user.setVip(1);
			user.setVipExpireTime(curr.getTime());
		}else {
			//续费VIP
			Calendar curr = Calendar.getInstance();
			if(user.getVipExpireTime().before(new Date())) {
				curr.setTime(new Date());
			}else {
				curr.setTime(user.getVipExpireTime());
			}
			//			if("1".equals(one.getExtend2())) { // 月
			//				curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+Integer.valueOf(one.getPayCode()));
			//			}else { // 天
			//				curr.set(Calendar.DATE,curr.get(Calendar.DATE)+Integer.valueOf(one.getPayCode()));
			//			}
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+Integer.valueOf(one.getPayCode()));
			user.setVip(1);
			user.setVipExpireTime(curr.getTime());
		}
		user.setVipLevel(Integer.valueOf(one.getExtend4()));
		user.setInviteCount(10);
		user.setUnlockWechat(Integer.valueOf(one.getExtend2()));
		user.setChatCount(Integer.valueOf(one.getExtend3()));
		user.setMessageCount(Integer.valueOf(one.getExtend5()));
//		Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKWECHATCOUNT);
//		if(null != object) {
//			user.setUnlockWechat(Integer.valueOf(object.toString()));
//		}
//		Object object2 = redisUtil.get(ProjectConstant.platformConstant.UNLOCKCHATCOUNT);
//		if(null != object2) {
//			user.setChatCount(Integer.valueOf(object2.toString()));
//		}
		userMapper.updateById(user);
	}

	/**
	 * 	添加账单流水
	 * @param orderNo		订单号
	 * @param type			类型
	 * @param businessType	业务类型
	 * @param amount		金额
	 * @param userId		支付userId
	 * @param toUserId		对方ID
	 * @param remark		描述
	 * @param source		数据源
	 * @param isSettle		0=异常  1=正常
	 * @param relatedId		业务ID
	 */
	private void addCapotalFlow(String orderNo,Integer type,Integer businessType,BigDecimal amount,Long userId,Long toUserId,String remark,Integer source,Integer isSettle,Long relatedId,String nameType) {
		UserCapitalFlow userCapitalFlow = userCapitalFlowService.getOne(new QueryWrapper<UserCapitalFlow>().eq("order_no", orderNo));
		if(null != userCapitalFlow) {
			userCapitalFlow.setIsSettle(isSettle);
			userCapitalFlowService.updateById(userCapitalFlow);
		}else {
			userCapitalFlow = new UserCapitalFlow();
			userCapitalFlow.setType(type);
			userCapitalFlow.setBusinessType(businessType);
			userCapitalFlow.setAmount(amount);
			userCapitalFlow.setUserId(userId);
			userCapitalFlow.setToUserId(toUserId);
			userCapitalFlow.setOrderNo(orderNo);
			userCapitalFlow.setRemark(remark);
			userCapitalFlow.setSource(source);
			userCapitalFlow.setRelatedId(relatedId);
			userCapitalFlow.setIsSettle(isSettle);
			userCapitalFlow.setNameType(nameType);
			userCapitalFlowService.save(userCapitalFlow);
		}
	}

	/**
	 * 	获取用户ID
	 * @return
	 */
	private Long getLoginUserId() {
		Object object = RequestContext.get("userInfo");
		if(null == object) {
			return null;
		}
		JWTUser jwtUser = (JWTUser) object;
		if(null == jwtUser || null == jwtUser.getId()) {
			return null;
		}
		return jwtUser.getId();
	}

	private String ambientType = "prod";
	@Override
	public AjaxResult applePay(String payload, String transactionId, Long businessId, Integer type,Long toUserId,
			HttpServletRequest request) {
		try {
			Long userId = getLoginUserId();
			if(null == userId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId).select(User::getId,User::getSex,User::getRegisterTime));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
//			if("F".equals(user.getSex())) {
//				String format = com.ruoyi.common.utils.date.DateUtils.format(user.getRegisterTime(), "yyyyMMdd");
//				if(Integer.valueOf(format) >= 20240906) {
//					return AjaxResult.error("当前账号不支持开通会员");
//				}
//			}
			boolean isTrue = iosCheck(transactionId, payload, "prod");
			if((ambientType.equalsIgnoreCase("dev") && isTrue) || (ambientType.equalsIgnoreCase("prod") && isTrue)) {
				PriceSetting priceSetting = priceSettingMapper.selectOne(new QueryWrapper<PriceSetting>().eq("id", businessId));
				if(null == priceSetting) {
					return AjaxResult.error("业务不存在");
				}
				//同步 
				synchronized(this) {
					OrderInfo order = getOne(new QueryWrapper<OrderInfo>().eq("trade_no", transactionId));
					if(null != order) {
						return AjaxResult.error("重复订单");
					}
				}
				OrderInfo orderInfo = new OrderInfo();
				//业务逻辑处理
				orderInfo.setCreateTime(new Date());
				orderInfo.setOrderCreateTime(new Date());
				orderInfo.setUpdateTime(new Date());
				orderInfo.setOrderAmount(priceSetting.getCurrentPrice());
				orderInfo.setActualAmount(priceSetting.getCurrentPrice());
				orderInfo.setOrderNo(OrderNumberGeneratorUtil.get());
				orderInfo.setOrderStatus("1");
				orderInfo.setPayType("4");//苹果支付
				orderInfo.setTradeNo(transactionId);
				orderInfo.setRelatedId(businessId);//业务ID
				orderInfo.setPayUserId(userId);//支付人
				if(null != toUserId && toUserId > 0) {
					orderInfo.setToUserId(toUserId);
				}
				orderInfo.setOrderType(String.valueOf(type));
				if(1 == type) {// VIP
					orderInfo.setRemark("开通VIP："+priceSetting.getCurrentPrice());
					save(orderInfo);
					rechargeUserVip(orderInfo.getPayUserId(),priceSetting,0L,orderInfo.getOrderNo(),orderInfo.getPayType());
					//添加账单流水信息
					addCapotalFlow(orderInfo.getOrderNo(), 2, 1, orderInfo.getOrderAmount(), orderInfo.getPayUserId(), 0L, "VIP充值", Integer.valueOf(orderInfo.getPayType()), 1, orderInfo.getRelatedId(),priceSetting.getPriceName());
					//taskAsync.completeaOpenVipTask(orderInfo.getPayUserId());
					// 分佣
					if(null != toUserId && toUserId > 0) {
						userTotalCapitalService.initUserTotalCapital("1", toUserId,orderInfo.getOrderAmount().multiply(new BigDecimal("0.5")),1);
					}
					return AjaxResult.success();
				}else if(6 == type) {// 虚拟币
					orderInfo.setRemark("钻石充值："+priceSetting.getCurrentPrice());
					save(orderInfo);
					BigDecimal amount = BigDecimal.ZERO;
					amount = priceSetting.getOriginalPrice();
					if (priceSetting.getCurrentPrice().compareTo(orderInfo.getActualAmount()) == 1){
						amount = orderInfo.getActualAmount();
					}
					//增加钻石
					userTotalCapitalService.initUserTotalCapital("3", orderInfo.getPayUserId(), amount, 1);
					//添加账单流水信息
					addCapotalFlow(orderInfo.getOrderNo(), 1, 4, orderInfo.getOrderAmount(), orderInfo.getPayUserId(), 1L, "钻石充值", Integer.valueOf(orderInfo.getPayType()), 1, orderInfo.getRelatedId(),priceSetting.getPriceName());
					return AjaxResult.success();
				}
			}
			return AjaxResult.error("验证失败");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络开小差啦");
		}
	}
	private boolean iosCheck(String transactionId, String payload,String ambientType) {
		//线上环境验证
		String verifyResult = IosVerifyUtil.buyAppVerify(payload, ambientType);
		if (verifyResult == null) {
			return false;
		} else {
			JSONObject appleReturn = JSONObject.parseObject(verifyResult);
			System.out.println("苹果校验打印数据："+appleReturn);
			String states = appleReturn.getString("status");
			//无数据则沙箱环境验证
			if ("21007".equals(states)) {
				verifyResult = IosVerifyUtil.buyAppVerify(payload, ambientType);
				System.out.println("沙箱1："+verifyResult);
				appleReturn = JSONObject.parseObject(verifyResult);
				System.out.println("沙箱2："+appleReturn);
				states = appleReturn.getString("status");
				return true;
			}
			// 前端所提供的收据是有效的    验证成功
			if (states.equals("0")) {
				String receipt = appleReturn.getString("receipt");
				JSONObject returnJson = JSONObject.parseObject(receipt);
				System.out.println("苹果校验打印2："+returnJson);
				String bundleId = "app.mida.com";
				if(!bundleId.equals(returnJson.getString("bid")) && !bundleId.equals(returnJson.getString("bundle_id"))){
					return false;
				}
				JSONArray inAppJsonArray = returnJson.getJSONArray("in_app");
				if (!CollectionUtils.isEmpty(inAppJsonArray)) {
					for(int i = 0 ; i < inAppJsonArray.size() ; i ++ ){
						JSONObject inAppJson = inAppJsonArray.getJSONObject(i);
						System.out.println("苹果校验打印3："+inAppJson);
						String transactionIdInApp = inAppJson.getString("transaction_id");
						if(transactionIdInApp.equals(transactionId)){
							//交易ID一致,返回OK
							return true;
						}
					}
					return false;
				}
				return false;
			} else {
				return false;
			}
		}
	}

	@Override
	public AjaxResult isRecharge() {
		Long userId = getLoginUserId();
		if(null == userId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId).select(User::getId,User::getSex,User::getRegisterTime));
		if(null == user) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if("F".equals(user.getSex())) {
			String format = com.ruoyi.common.utils.date.DateUtils.format(user.getRegisterTime(), "yyyyMMdd");
			if(Integer.valueOf(format) >= 20240906) {
				return AjaxResult.error("当前账号不支持开通会员");
			}
		}
		return AjaxResult.success();
	}
}
